package org.tao.lightningmq.nameserver.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.common.event.EventBus;
import org.tao.lightningmq.common.tcp.TcpMsgDecoder;
import org.tao.lightningmq.common.tcp.TcpMsgEncoder;
import org.tao.lightningmq.nameserver.handler.TcpNettyServerHandler;

/**
 * @Author lht
 * @date 2025/1/7 - 15:00
 * @description: nameserver的netty服务启动类
 */
public class NameServerNettyStarter {

    private static final Logger LOGGER = LoggerFactory.getLogger(NameServerNettyStarter.class);
    private final int port;

    public NameServerNettyStarter(int port) {
        this.port = port;
    }

    public void startServer() {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        TcpNettyServerHandler tcpNettyServerHandler = new TcpNettyServerHandler(new EventBus("broker-connection-"));
        bootstrap.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(new TcpMsgDecoder());
                ch.pipeline().addLast(new TcpMsgEncoder());
                ch.pipeline().addLast(tcpNettyServerHandler);
            }
        });
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            LOGGER.info("nameserver服务关闭");
        }));
        try {
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            LOGGER.info("nameserver服务启动成功，端口号：{}", port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            LOGGER.warn("nameserver服务启动失败", e);
        }
    }
}
